#include "Monster.h"
#include "Character/MovePart.h"
#include "Character/SkillPart.h"
#include "Character/PlayerMgr.h"
#include "Common/AttrMgr/AttrMgr.h"
#include "MonsterMgr.h"
#include "MonsterRefMgr.h"
#include "base/core/utility.h"
#include "Character/monster/MonsterRefCfg.h"
#include "Common/CampDefine.h"

#include "Common/TableData/MonsterMonsterCfg.h"
#include "Common/TableData/ConstantConstantCfg.h"
#include "Common/TableData/SkillSkillCfg.h"

#include "Character/npc/Npc.h"
#include "Character/newAI/behaviac/BehaviacAIManager.h"
#include "Character/newAI/behaviac/CreatureCommonAI.h"
#include "../CreatureMgr.h"
#include "../../Effect/EffectMgr.h"
#include "base/core/Profiler.h"
const uint32_t g_constCalcExpRang = 60;  //单位米

Monster::Monster()
{
	m_creatureKind = CREATURE_MONSTER;
	m_sightRange = 25.0f;
	m_viewAngle = 0.0f;
	m_monsterCfgInfo = nullptr;
	m_corpseTime = 0;
	//m_fspeed = 0.0f;
	m_formationId = 0;
	m_monsIdx = -1;
	m_byteHaveBopiNum = 0;
	m_monsterId = 0;

	m_dropState = MonsterDropOwnerState_None;
	m_dropOwnerID = 0;

	m_existTime = 0;
	m_bIsDeadBeback = false;
	m_bIsBornFlag = false;
	m_stExtendInfo.set_campid(0);
	m_stExtendInfo.set_mastercid(0);
	m_stExtendInfo.set_unionid(0);
	m_stExtendInfo.set_level(0);
	m_stExtendInfo.set_mastername("");
	m_stExtendInfo.set_teamid(0);

	m_dir = Point3<float>(0,0,1);
	m_aitimeafterborn = 0;
	m_i64KillerID = 0;
	m_modelScale = Point3<float>(1.0, 1.0, 1.0);
}

Monster::~Monster()
{
	m_monsterCfgInfo = nullptr;
}

bool Monster::Init()
{
	memset(m_attrs, 0, sizeof(uint32_t)*M_MAX);
	memset(m_attrs64, 0, sizeof(uint64_t)*M_ATTR_ULONG_END);
	for (size_t i = 0; i < PART_MAX; i++)
	{
		m_pPart[i] = nullptr;
	}

	m_monsterCfgInfo = g_GetMonsterMonsterCfgTable()->GetMonsterMonsterCfgInfo(m_monsterId);
	if (m_monsterCfgInfo == nullptr)
	{
		LogErrFmtPrint("in the monster table, monster id:%d is not exist", m_monsterId);
		return false;
	}

	
	//初始化怪物部件
	m_pPart[PART_MOVE] = g_GetCreatureMgr()->CreatePart(PART_MOVE, dynamic_cast<Creature*>(this));
	if (!m_pPart[PART_MOVE])
		return false;
	m_pPart[PART_SKILL] = g_GetCreatureMgr()->CreatePart(PART_SKILL, dynamic_cast<Creature*>(this));
	if (!m_pPart[PART_SKILL])
		return false;
	m_pPart[PART_BUFF] = g_GetCreatureMgr()->CreatePart(PART_BUFF, dynamic_cast<Creature*>(this));
	if (!m_pPart[PART_BUFF])
		return false;



	//if (ENUM_MONSTER_TYPE_BOSS_TA == GetMonsterType())
	//{
	//	m_bSee = true;
	//}


	//注册被击事件
	g_GetEvent()->Subscribe(this, EVENT_UNDER_ATTACK,m_Cid,0,"monst register attack event");
	g_GetEvent()->Subscribe(this, EVENT_ATTACK_SOMEBODY,m_Cid,0,"monst register attack event");

	return true;
}

bool Monster::UnInit()
{
	memset(m_attrs, 0, sizeof(uint32_t)*M_MAX);

	for (int32_t i = 0; i < PART_MAX; i++)
	{
		if (m_pPart[i])
		{
			g_GetCreatureMgr()->RecylePart(m_pPart[i]);
			m_pPart[i] = nullptr;
		}
	}
	m_formationId = 0;
	m_monsIdx = -1;

	m_dropState = MonsterDropOwnerState_None;
	m_dropOwnerID = 0;

	g_GetEvent()->UnSubscribeAll(this);
	g_GetTimerAxis()->KillAllTimer(this);

	g_GetGeneralCreatureRefMgr()->monsterDead(m_sceneId, m_Cid);
	Creature::UnInit();
	return true;
}

bool Monster::InitAttr(uint32_t monsterId)
{
	if (m_monsterCfgInfo->monsterLV > 0)
	{
		m_stExtendInfo.set_level(m_monsterCfgInfo->monsterLV);
	}
	
	stMonsterConfig * pMonsterParam=g_GetMonsterMgr()->GetMonsterConfigParam(monsterId);
	if (!pMonsterParam)
	{
		LogDebugFmtPrint("find monster error monsterid = %d",monsterId);
		return false;
	}

	m_attrs64[M_MAX_HP] = GetMonsterAttrFormula(pMonsterParam->_maxHP);
	if (m_monsterCfgInfo->hpSectionNum > 1)
	{
		m_attrs64[M_MAX_HP] = m_attrs64[M_MAX_HP] * m_monsterCfgInfo->hpSectionNum;
	}
	m_attrs64[M_HP] = m_attrs64[M_MAX_HP];
	m_attrs[M_MAX_MP] = GetMonsterAttrFormula(pMonsterParam->_maxMP);
	m_attrs[M_MP] = m_attrs[M_MAX_MP];
	//m_attrs64[M_HP] = m_attrs64[M_MAX_HP];


	SetAttrMA(M_LEVEL, m_stExtendInfo.level());
	SetAttrMA(g_GetAttrMgr()->GetMonsterLevMNumAttr(C_AP), GetMonsterAttrFormula(pMonsterParam->_ap));
	SetAttrMA(g_GetAttrMgr()->GetMonsterLevMNumAttr(C_MAT), GetMonsterAttrFormula(pMonsterParam->_mat));
	SetAttrMA(g_GetAttrMgr()->GetMonsterLevMNumAttr(C_DP), GetMonsterAttrFormula(pMonsterParam->_dp));
	SetAttrMA(g_GetAttrMgr()->GetMonsterLevMNumAttr(C_MDP), GetMonsterAttrFormula(pMonsterParam->_mdp));
	SetAttrMA(g_GetAttrMgr()->GetMonsterLevMNumAttr(C_PHYHIT), GetMonsterAttrFormula(pMonsterParam->_phyHit));
	SetAttrMA(g_GetAttrMgr()->GetMonsterLevMNumAttr(C_MAGHIT), GetMonsterAttrFormula(pMonsterParam->_magHit));
	SetAttrMA(g_GetAttrMgr()->GetMonsterLevMNumAttr(C_PHYDODGE), GetMonsterAttrFormula(pMonsterParam->_phyDodge));
	SetAttrMA(g_GetAttrMgr()->GetMonsterLevMNumAttr(C_MAGDODGE), GetMonsterAttrFormula(pMonsterParam->_magDodge));
	SetAttrMA(g_GetAttrMgr()->GetMonsterLevMNumAttr(C_PHYCRIT), GetMonsterAttrFormula(pMonsterParam->_phyCrit));
	SetAttrMA(g_GetAttrMgr()->GetMonsterLevMNumAttr(C_MAGCRIT), GetMonsterAttrFormula(pMonsterParam->_magCrit));
	SetAttrMA(g_GetAttrMgr()->GetMonsterLevMNumAttr(C_PHYTOUGHNESS), GetMonsterAttrFormula(pMonsterParam->_phyToughness));
	SetAttrMA(g_GetAttrMgr()->GetMonsterLevMNumAttr(C_MAGTOUGHNESS), GetMonsterAttrFormula(pMonsterParam->_magToughness));
	SetAttrMA(g_GetAttrMgr()->GetMonsterLevMNumAttr(C_FIREDEF), GetMonsterAttrFormula(pMonsterParam->_fireDef));
	SetAttrMA(g_GetAttrMgr()->GetMonsterLevMNumAttr(C_ICEDEF), GetMonsterAttrFormula(pMonsterParam->_iceDef));

	SetAttrMA(g_GetAttrMgr()->GetMonsterLevMNumAttr(C_WINDDEF), GetMonsterAttrFormula(pMonsterParam->_windDef));
	SetAttrMA(g_GetAttrMgr()->GetMonsterLevMNumAttr(C_SOLDEF), GetMonsterAttrFormula(pMonsterParam->_solDef));
	SetAttrMA(g_GetAttrMgr()->GetMonsterLevMNumAttr(C_RAYDEF), GetMonsterAttrFormula(pMonsterParam->_rayDef));
	SetAttrMA(g_GetAttrMgr()->GetMonsterLevMNumAttr(C_POISONDEF), GetMonsterAttrFormula(pMonsterParam->_poisonDef));
	SetAttrMA(g_GetAttrMgr()->GetMonsterLevMNumAttr(C_PHYCRITMUL), GetMonsterAttrFormula(pMonsterParam->_phyCritMul));
	SetAttrMA(g_GetAttrMgr()->GetMonsterLevMNumAttr(C_MAGCRITMUL), GetMonsterAttrFormula(pMonsterParam->_magCritMul));
	//m_attrs[M_MSPEED] = m_monsterCfgInfo->mSpeed;
	//m_fspeed = m_monsterCfgInfo->mSpeed / 1000.0f;
	SetAttrMA(g_GetAttrMgr()->GetMonsterLevMNumAttr(C_MSPEED), m_monsterCfgInfo->mSpeed, false);

	if (m_monsterCfgInfo->viewType == ENUM_MONSTER_VIEW_TYPE_CIRCLE ||
		m_monsterCfgInfo->viewType == ENUM_MONSTER_VIEW_TYPE_BALL)
	{
		if ((int)pMonsterParam->_view.size()<1)
		{
			LogDebugFmtPrint("monsterid=%d view  error",monsterId);
			return false;
		}
#ifdef AI_DEBUG
		m_sightRange = pMonsterParam->_view[0] * 2 / 1000.0f;
#else
		m_sightRange = pMonsterParam->_view[0] / 1000.0f;
#endif

		if (m_monsterCfgInfo->pursueRange < m_sightRange * 1000)
		{
			LogErrFmtPrint("the monsterId:%d sight range > purse range", m_monsterId);
		}
	}
	else if (m_monsterCfgInfo->viewType == ENUM_MONSTER_VIEW_TYPE_SECTOR)
	{
		//std::vector<std::string> vec;
		//CommonApi::SplitStr(m_monsterCfgInfo->view.c_str(), ",", &vec);

		if (pMonsterParam->_view.size() != 2)
		{
			m_sightRange = 25.0f;//	
		}
		else
		{
			m_sightRange = pMonsterParam->_view[0] / 1000.0f;
			m_viewAngle = pMonsterParam->_view[1];
		}
	}
	if (m_monsterCfgInfo->campPrefer>0)
	{
		SetMonsterCampID(m_monsterCfgInfo->campPrefer);
	}
	
	//初始化怪物的技能属性
	SkillPart* pSkillPart = static_cast<SkillPart*>(GetPart(PART_SKILL));
	if (pSkillPart == nullptr)
		return false;
	for (int i = 0; i < (int)pMonsterParam->_normalSkill.size(); i++)
	{
		const SkillCfg *pInfo = g_GetSkillMgr()->GetSkillCfg(pMonsterParam->_normalSkill[i]);
		if (pInfo != nullptr)
		{
			if (this->GetParentMonsterType() == PARENT_MONSTER_TYPE_SUMMON && m_monsterCfgInfo->monsterLV == 0)
			{
				pSkillPart->AddSkill(pInfo->skillID, m_stExtendInfo.level(), 0, 0, false, false);
			}
			else
			{
				pSkillPart->AddSkill(pInfo->skillID, 1, 0, 0, false, false);
			}
		}
	}

	const AiAiCfgInfo *pInfo = g_GetAiAiCfgTable()->GetAiAiCfgInfo(m_monsterCfgInfo->specialAI);
	if (pInfo)
	{
		std::vector<int> initSkill;
		CommonApi::SplitStrToVecInt(pInfo->initSkills, ",", &initSkill);
		if (initSkill.size() > 0 && initSkill.size() % 3 == 0)
		{
			for (uint32_t i = 0; i < initSkill.size(); i += 3)
			{
				int skillId = initSkill[i];
				int priority = initSkill[i + 1];
				int time = initSkill[i+2];
				if (this->GetParentMonsterType() == PARENT_MONSTER_TYPE_SUMMON && m_monsterCfgInfo->monsterLV == 0)
				{
					pSkillPart->AddSkill(skillId, m_stExtendInfo.level(), 0, priority, false, false);
				}
				else
				{
					pSkillPart->AddSkill(skillId, 1, 0, priority, false, false);
				}

				stSkillInfo* pSkillInfo = pSkillPart->GetSkillInfo(skillId);
				if (pSkillInfo)
				{
					pSkillInfo->_cdTimeStamps = Time::Now().UnixMSec() - pSkillInfo->_pSkillmeta->cd + time;
				}
			}
		}

		std::vector<int> groupSkills;
		CommonApi::SplitStrToVecInt(pInfo->randomSklGroup, ",", &groupSkills);
		if (groupSkills.size() > 0)
		{
			for (uint32_t i = 0; i < groupSkills.size(); i++)
			{
				int skillId = groupSkills[i];
				pSkillPart->AddSkill(skillId, 1, 0, 0,false,false);
				if (this->GetParentMonsterType() == PARENT_MONSTER_TYPE_SUMMON && m_monsterCfgInfo->monsterLV == 0)
				{
					pSkillPart->AddSkill(skillId, m_stExtendInfo.level(), 0, 0,false,false);
				}
				else
				{
					pSkillPart->AddSkill(skillId, 1, 0, 0,false,false);
				}
			}
		}
	}

	if (GetParentMonsterType() == PARENT_MONSTER_TYPE_MOVE_BIAOCHE
		|| GetParentMonsterType() == PARENT_MONSTER_TYPE_MOVE_TEAM_BIAOCHE)
	{
		m_aiData = g_GetBehaviacAIMgr()->CreateAI("AI_BiaoChe_00", m_Cid);
	}
	else if (GetParentMonsterType() == PARENT_MONSTER_TYPE_CAN_TRAP ||
			GetParentMonsterType() == PARENT_MONSTER_TYPE_TRAP_CAN_BE_ATTATED)
	{
		m_aiData = g_GetBehaviacAIMgr()->CreateAI("AI_XIANJING_00", m_Cid);
	}
	else if (GetParentMonsterType() == PARENT_MONSTER_TYPE_CAN_TRIGGER_THING)
	{
		m_aiData = g_GetBehaviacAIMgr()->CreateAI("AI_TrigItem_00", m_Cid);
	}
	else if (GetParentMonsterType() == PARENT_MONSTER_TYPE_MOVE_BIAOCHE_MONSTER)
	{
		m_aiData = g_GetBehaviacAIMgr()->CreateAI("AI_BiaoCheMonster_00", m_Cid);
	}
	else if (GetParentMonsterType() == PARENT_MONSTER_TYPE_CAN_USE_THING
			|| GetParentMonsterType() == PARENT_MONSTER_TYPE_CAN_USE_DROP)
	{
		m_aiData = g_GetBehaviacAIMgr()->CreateAI("AI_UseItemMonster_00", m_Cid);
	}
	else if (GetParentMonsterType() == PARENT_MONSTER_TYPE_CAN_DESTROYED_THING)
	{
		m_aiData = g_GetBehaviacAIMgr()->CreateAI("AI_DestroyedMonster_00", m_Cid);
	}
	else if (GetParentMonsterType() == PARENT_MONSTER_TYPE_NO_MOVE_BOSS)
	{
		m_aiData = g_GetBehaviacAIMgr()->CreateAI("AI_BOSS_NOMOVE_00", m_Cid);
		if (m_aiData && pInfo)
		{
			std::vector<int> bossSkill;
			CommonApi::SplitStrToVecInt(pInfo->bossSkill, ",", &bossSkill);
			if (bossSkill.size() >= 2)
				g_GetEvent()->Subscribe(dynamic_cast<IEventExecuteSink*>(m_aiData), EVENT_ACTIVITY_STOP, 0, 0, NULL);
		}
	}
	else if (GetParentMonsterType() == PARENT_MONSTER_TYPE_BOSS_ZHONGSHEN)
	{
		m_aiData = g_GetBehaviacAIMgr()->CreateAI("AI_BOSS_ZHONGSHEN_00", m_Cid);
	}
	else if (GetParentMonsterType() == PARENT_MONSTER_TYPE_SUMMON)
	{
		if (this->GetMonsterFightType() == 5)
		{
			m_aiData = g_GetBehaviacAIMgr()->CreateAI("AI_MoveSummon_00", m_Cid);
		}
		else
		{
			m_aiData = g_GetBehaviacAIMgr()->CreateAI("AI_Summon_00", m_Cid);
		}
	}
	else
	{
		m_aiData = g_GetBehaviacAIMgr()->CreateAI("MonsterCommonAI", m_Cid);
	}

	if (m_aiData == nullptr)
	{
		return false;
	}
	m_aiData->Init(this);


	//怪物存在时间
	if (m_monsterCfgInfo->liveTime > 0)
	{
		g_GetTimerAxis()->SetTimer(enTimeID_ExistTime, m_monsterCfgInfo->liveTime, this, 1);
	}

	return true;
}

bool Monster::Born(CharIDType monsterCid, uint32_t monsterId, uint32_t sceneId, Point3<float>& bornPos, MonsCreateParam &createParam, Point3<float>& dir, int32_t monsIdx/* = -1*/, MonsterExtendInfo * pExtend, uint32_t groupId)
{
	m_Cid = monsterCid;
	m_monsterId = monsterId;
	m_curstate = State_normal;
	m_bornPos = bornPos;
	m_monsIdx = monsIdx;
	m_bIsBornFlag = true;
	m_monsterGroupId = groupId;
	m_dir = dir;
	m_createParam = createParam;
	if (pExtend)
	{
		m_stExtendInfo.CopyFrom(*pExtend);
	}

	bool ret = Init();
	if (ret == false)
	{
		return false;
	}

	ret = InitAttr(monsterId);
	if (ret == false)
	{
		return false;
	}
	STransParam transParam;
	transParam.transType = ETransType_Born;
	if (!EnterScene(sceneId, bornPos, transParam))
	{
		return false;
	}

	OnDoEffect(true);

	//m_bIsBornFlag = false;

	g_GetTimerAxis()->SetTimer(enTimeID_BornFlag, g_IntervalBornFlag, this, 1);

	return true;
}

void Monster::Update(uint64_t tick)
{
}

void Monster::OnCorpse()
{
	//怪物尸体时间到了 表示可以从场景移除 并且需要设置以下生物的destory标记
	//CreatureMgr会读取生物的destory标记进行做内存回收操作 MonsterMgr不需要管内存回收
	if (LeaveScene())
	{
		//LogDebugFmtPrint("Monster::OnCorpse  LeaveScene() sccueed");
		//下一帧准备等待回收
		//g_GetCreatureMgr()->WaitDestory(GetCid());
		g_GetCreatureMgr()->WaitDestory((Creature*)this);
	}
}

void Monster::OnDead(CharIDType killerCid)
{
	//即将死亡状态下的BUFF处理, 防止死循环
	if (IsWillDead() == false)
	{
		SetWillDead(true);
		g_GetEvent()->FireExecute(EVENT_CREATURE_WILLING_DIED, m_Cid, 0, nullptr, 0);
	//	//if (GetAttr(C_HP) > 0)
	//	//{
	//	//	SetWillDead(false);
	//	//	return;
	//	//}
	//	//SetWillDead(false);
	}

	if (!IsDead())
	{
		m_i64KillerID = killerCid;
		//Creature * pCreature = g_GetCreatureMgr()->GetCreature(killerCid);
		
		StopMove(false);

		OnDoEffect(false);  //置死亡状态前，先处理这个效果

		BuffEffect_CleanupAllFadeOutEffects(BuffInfoDeadEnd);

		Creature::OnDead(killerCid);

		DieEvent dieEvent;
		dieEvent.killerCid = m_i64KillerID;
		dieEvent.count = 1;
		dieEvent.sceneId = m_sceneId;
		dieEvent.nCid = m_Cid;
		dieEvent.monsterId = GetConfigId();
		dieEvent.dropOwnerCid = m_dropOwnerID;
		dieEvent.planUid = GetPlaneID();
		dieEvent.nType = m_monsterCfgInfo->monsterType;
		dieEvent.nCfgType = m_monsterCfgInfo->monsterCfgType;
		dieEvent.createType = m_createParam.createType;
		dieEvent.createTypeVal = m_createParam.createTypeVal;
		//获取该怪物仇恨列表的人
		dieEvent.hateTargetList = GetMonsterKillerList(&dieEvent.mapTargetTeamMem);
		//GetHateListID(dieEvent.hateTargetList);
		

		//后面判断是否有尸体时间

		m_corpseTime = g_GetGlobalServerTime()->Tick() + GetMonsterInfo()->bodyStayTime;
		//CTODO 要考虑生物死亡后是否要将生物各个部件的定时器进行清除操作 这个应该要放到死亡做

		if (m_monsterGroupId > 0)
		{
			g_GetCreatureMgr()->MonsterGroupDelMonster(GetSceneId(), m_monsterGroupId, this);
		}

		g_GetTimerAxis()->SetTimer(enTimeID_CorpseTime, GetMonsterInfo()->bodyStayTime, this, 1);
		/*
		怪物死亡事件
		nSrcID: 怪被击杀的生物CID
		bySrcType:怪物自身生物类型
		*/
		g_GetEvent()->FireExecute(EVENT_CREATURE_DEAD, killerCid, m_creatureKind, (DieEvent*)&dieEvent, sizeof(dieEvent));
		LogDebugFmtPrint("monster ondead, monsterId:%u, dropOwnerCid:%llu ", dieEvent.monsterId, m_dropOwnerID);
		
	}
}

void Monster::OnRevive(uint64_t saverCid)
{
	
	SetAttrMA(M_HP, GetAttr(C_MAX_HP));
	SetAttrMA(M_MP, GetAttr(C_MAX_MP));

	g_GetTimerAxis()->KillTimer(enTimeID_CorpseTime,this);
	Creature::OnRevive(saverCid);
}

bool Monster::IsInCorpseTime()
{
	return m_corpseTime > g_GetGlobalServerTime()->Tick();
}


void    Monster::OnDestroyMonsterNow()
{
	m_corpseTime = g_GetGlobalServerTime()->Tick();
	g_GetTimerAxis()->KillTimer(enTimeID_CorpseTime, this);
	OnCorpse();
}


int64_t Monster::GetAttr(uint32_t CANum)
{
	uint32_t MANum = GetAttrNum(CANum);
	if (MANum == M_NONE || MANum >= M_MAX)
	{
		//错误打印，访问怪物没有的属性
		//LogErrFmtPrint("Monster::GetAttr error %d", CANum);
		return M_NONE;
	}
	if (MANum>M_ATTR_ULONG_END)
	{
		return m_attrs[MANum];
	}
	else
	{
		return m_attrs64[MANum];
	}
}

//int64_t Monster::GetPAttrValue(uint32_t attrPANum)
//{
//	if (attrPANum > P_NONE && attrPANum < P_MAX)
//	{
//		return m_attrs[attrPANum];
//	}
//	return 0;
//}

uint32_t Monster::GetAttrNum(uint32_t CommonAttrNum)
{
	return g_GetAttrMgr()->GetMAttr(CommonAttrNum);
}

void Monster::SetAttr(uint32_t CANum, int64_t attrValue, bool syn /* = false */)
{
	uint32_t MANum = GetAttrNum(CANum);
	SetAttrMA(MANum, attrValue, syn);
	return;
}

void  Monster::SetAttrMA(uint32_t MANum, int64_t attrValue, bool syn/* = false*/)
{
	if (MANum == M_NONE || MANum > M_MAX)
	{
		return;
	}

	if (MANum>M_ATTR_ULONG_END)
	{
		if (MANum<M_USE_ATTR_END && !g_GetAttrMgr()->IsCanNegativeMAttr(MANum))
		{
			m_attrs[MANum] = attrValue > 0 ? attrValue : 0;
		}
		else
		{
			m_attrs[MANum] = attrValue;
		}
	}
	else
	{
		m_attrs64[MANum] = attrValue > 0 ? attrValue : 0;
	}
	AttrsFormula(MANum, 0, syn);

	if (MANum == M_HP && m_attrs64[MANum] == 0)
	{
		syn = true;  //如果是血量，且达到了死亡状态 ，则时实同步
		OnDead(m_Cid);
		//LogErrFmtPrint("er::SetAttrMA  someone sethp=0, error cid= %d", m_Cid);
	}

	if (MANum<M_USE_ATTR_END)
	{
		SynAttrCache(MANum);
	}

	if (syn)
	{
		SynAttrToClient();
	}

}

bool Monster::AddAttr(uint32_t CANum, int64_t attrValue, bool syn, uint64_t relationCid /* = 0 */)
{
	uint32_t MANum = 0;
	BEGIN_PROFILE("GetAttrNum");
	 MANum = GetAttrNum(CANum);
	END_PROFILE();
	if (MANum == M_NONE || MANum > M_MAX)
	{
		//错误打印，访问怪物没有的属性
		LogErrFmtPrint("Monster::AddAttr error %d", CANum);
		return false;
	}
	return  AddAttrMA(MANum, attrValue, syn, relationCid);
}

bool  Monster::AddAttrMA(uint32_t MANum, int64_t attrValue, bool syn, uint64_t relationCid/* = 0*/)
{
	
	if (MANum == M_NONE || MANum >= M_MAX)
	{
		return false;
	}

	if (attrValue == 0)
		return false;

	if (MANum>M_ATTR_ULONG_END)
	{
		//防止溢出
		if (attrValue < 0)
		{
			if (!g_GetAttrMgr()->IsCanNegativeMAttr(MANum) && MANum<M_USE_ATTR_END) //允许为负的不管
			{
				int32_t absValue = abs(attrValue);
				m_attrs[MANum] = ((m_attrs[MANum] > absValue) ? (m_attrs[MANum] - absValue) : 0);
			}
			else
			{
				m_attrs[MANum] += attrValue;
			}
		}
		else
		{
			//
			m_attrs[MANum] = m_attrs[MANum] + (uint32_t)attrValue;
		}
	}
	else
	{
		//防止溢出
		if (attrValue < 0)
		{
			int64_t absValue = abs(attrValue);
			m_attrs64[MANum] = ((m_attrs64[MANum] > absValue) ? (m_attrs64[MANum] - absValue) : 0);
		}
		else
		{
			//
			m_attrs64[MANum] = m_attrs64[MANum] + (uint64_t)attrValue;
		}
	}

	//血减少触发事件
	if (attrValue < 0 && M_HP == MANum)
	{
		g_GetEvent()->FireExecute(EVENT_HP_CHANGE, m_Cid, 0, nullptr, 0);
	}

	if (M_HP == MANum && m_attrs64[M_HP] >m_attrs64[M_MAX_HP] )
	{
		m_attrs64[M_HP] = m_attrs64[M_MAX_HP];
	}
	else if (M_MP == MANum && m_attrs64[M_MP] >m_attrs64[M_MAX_MP])
	{
		m_attrs[M_MP] = m_attrs64[M_MAX_MP];
	}

	if (MANum == M_HP && m_attrs64[MANum] == 0)
	{
		OnDead(relationCid);
	}
	
	//影响其他属性公式
	AttrsFormula(MANum, relationCid, syn);
	
	if (syn)
	{
		SynAttrCache(MANum);
		SynAttrToClient();
	}
	
	return true;
}

bool  Monster::AttrsFormula(uint32_t MANum, uint64_t relationCid, bool cache)
{
	if (MANum < M_USE_ATTR_END && !g_GetAttrMgr()->IsCanNegativeMAttr(MANum))
	{
		//基础属性进来，都是已加好的，不用再执行加法
		return false;
	}

	//是否含有百分比的
	AttrMgr::VecAttr *pVecMapPer = g_GetAttrMgr()->GetMAddAtrrsFormulaHasPer(MANum);
	if (!pVecMapPer || pVecMapPer->size() < 3)
	{
		AttrMgr::VecAttr *pVecMap = g_GetAttrMgr()->GetMAddAttrsFormula(MANum);
		if (!pVecMap || pVecMap->size() < 2)
			return false;

		AttrMgr::VecAttr& vecMap = *pVecMap;

		int64_t value = 0;

		if (vecMap[0] == M_HP ||
			vecMap[0] == M_MP)
		{
			return false;
		}

		for (uint32_t i = 1; i < vecMap.size(); i++)
			value += m_attrs[vecMap[i]];
		//只缓存，同步客户端在外层处理
		SetAttrMA(vecMap[0], value, true);
	}
	else
	{
		AttrMgr::VecAttr& vecMap = *pVecMapPer;

		int64_t value = 0;
		for (uint32_t i = 2; i < vecMap.size(); i++)
			value += m_attrs[vecMap[i]];

		//最后算百分比
		value = value*(1 + m_attrs[vecMap[1]] / 10000.0f);


		//只缓存，同步客户端在外层处理
		SetAttrMA(vecMap[0], value);

	}

	if (MANum == M_MAXHPRATE)
	{
		SetAttrMA(M_HP, m_attrs[M_HP] * (1 + m_attrs[MANum] / 10000.0f));
	}
	else if (MANum == M_MAXMPRATE)
	{
		SetAttrMA(M_MP, m_attrs[M_MP] * (1 + m_attrs[MANum] / 10000.0f));
	}



	return true;
}

void  Monster::SynAttrCache(uint32_t MANum)
{
	if (MANum == M_NONE || MANum >= M_MAX)
	{
		return;
	}

	if (g_GetAttrMgr()->IsBroadcastMAttr(MANum))
	{
		/*
		ProtoBuf::Attr* pAttr = m_attrBroadcastClient.add_creatureattrs();
		pAttr->set_attrnum(MANum);
		pAttr->set_attrvalue(m_attrs[MANum]);
		*/
		if (MANum>M_ATTR_ULONG_END)
		{
			m_attrsBroadCastCache[MANum] = m_attrs[MANum];
		}
		else
		{
			m_attrs64BroadCastCache[MANum] = m_attrs64[MANum];
		}
	}
}


void Monster::GetVisibleDataToClient(CreaturesCreateData& cvData)
{
	CreaturesCreateData::Monster *pmonsterData = cvData.add_monsters();
	pmonsterData->set_hp(m_attrs64[M_HP]);
	pmonsterData->set_maxhp(m_attrs64[M_MAX_HP]);
	pmonsterData->set_monsterconfigid(m_monsterId);
	pmonsterData->set_posx(m_pos.x);
	pmonsterData->set_posy(m_pos.y);
	pmonsterData->set_posz(m_pos.z);
	pmonsterData->set_curstate(m_curstate);
	pmonsterData->set_monstercid(m_Cid);
	pmonsterData->set_mspeed(m_attrs[M_MSPEED]/1000.0f);
	pmonsterData->set_idx(m_monsIdx);
	pmonsterData->set_lastusemonstertime(m_attrs[M_LAST_USE_MONSTER_TIME]);
	//pmonsterData->set_isrun(m_runStatus);
	pmonsterData->set_isnewcreate(m_bIsBornFlag);
	MovePart * pPart = dynamic_cast<MovePart*>(m_pPart[PART_MOVE]);
	if (pPart)
	{
		ActorMove actormove;
		ActorRockerMove rockmove;
		pPart->GetMoveingState(actormove, rockmove);
		if (pPart->GetMoveFlag() == enMovingFlag_Mouse)
		{
			ActorMove *pActormove = pmonsterData->mutable_actormove();
			pActormove->CopyFrom(actormove);
		}
	}
	MonsterExtendInfo* pExtendInfo=pmonsterData->mutable_extendinfo();
	pExtendInfo->CopyFrom(m_stExtendInfo);

	BuffPart * pBuffPart = dynamic_cast<BuffPart*>(m_pPart[PART_BUFF]);
	if (pBuffPart)
	{
		msgBuffList * pList = pmonsterData->mutable_bufflist();
		pBuffPart->GetAllBuffInfo(pList);
	}

}

void Monster::GetMoveDataToClient(ActorMove &mouseMove, ActorRockerMove &rockmove)
{
	MovePart * pPart = dynamic_cast<MovePart*>(m_pPart[PART_MOVE]);
	if (pPart)
	{
		pPart->GetMoveingState(mouseMove, rockmove);
	}
}

void Monster::SetAttrCache(uint32_t CANum, int64_t attrValue)
{

}

bool Monster::AddAttrCache(uint32_t CANum, int64_t attrValue, uint64_t relationCid)
{
	return true;
}

int Monster::GetMonsterFightType() const
{
	return m_monsterCfgInfo->monsterFightType;
}

MonsterType Monster::GetMonsterType() const
{
	if (m_monsterCfgInfo->monsterType <= ENUM_MONSTER_TYPE_NONE || m_monsterCfgInfo->monsterType >= ENUM_MONSTER_TYPE_MAX)
	{
		return ENUM_MONSTER_TYPE_NONE;
	}

	return (MonsterType)m_monsterCfgInfo->monsterType;
}

MonsterCfgType Monster::GetMonsterCfgType() const
{
	if (m_monsterCfgInfo->monsterCfgType <= ENUM_MONSTER_CFG_TYPE_NONE || m_monsterCfgInfo->monsterCfgType >= ENUM_MONSTER_CFG_TYPE_MAX)
	{
		return ENUM_MONSTER_CFG_TYPE_NONE;
	}

	return (MonsterCfgType)m_monsterCfgInfo->monsterCfgType;
}

ParentMonsterType Monster::GetParentMonsterType() const
{
	if (m_monsterCfgInfo->parentType <= PARENT_MONSTER_TYPE_NONE ||
			m_monsterCfgInfo->parentType >= PARENT_MONSTER_TYPE_MAX)
	{
		return PARENT_MONSTER_TYPE_NONE;
	}
	return (ParentMonsterType)m_monsterCfgInfo->parentType;
}

bool	Monster::IsMonsterTa() const
{
	if (m_monsterCfgInfo->parentType == PARENT_MONSTER_TYPE_TA)
	{
		return true;
	}
	return false;
}

MonsterViewType Monster::GetMonsterViewType() const
{
	if (m_monsterCfgInfo->viewType <= ENUM_MONSTER_VIEW_TYPE_NONE || m_monsterCfgInfo->viewType >= ENUM_MONSTER_VIEW_TYPE_MAX)
	{
		return ENUM_MONSTER_VIEW_TYPE_NONE;
	}

	return (MonsterViewType)m_monsterCfgInfo->viewType;
}

void Monster::FindCreatureInScene(Uint64Lst& clist)
{
	//根据提供的坐标位置，找对应场景里的生物
	Scene *pScene = g_GetSceneMgr()->GetScene(m_sceneId);
	if (!pScene)
		return;

	if (GetMonsterViewType() == ENUM_MONSTER_VIEW_TYPE_CIRCLE)
	{
		pScene->FindCreatureInCircle(clist, m_pos, m_sightRange);
	}
	else if (GetMonsterViewType() == ENUM_MONSTER_VIEW_TYPE_SECTOR)
	{
		pScene->FindCreatureInSector(clist, m_pos, m_dir, m_viewAngle, m_sightRange);
	}
	else if (GetMonsterViewType() == ENUM_MONSTER_VIEW_TYPE_BALL)
	{
		pScene->FindCreatureInBall(clist, m_pos, m_sightRange);
	}
}

Part* Monster::GetPart(uint32_t partType)
{
	if (!m_pPart[partType])
		return nullptr;
	return m_pPart[partType];
}

bool Monster::HasBuffStateBag(uint32_t stateBagId)
{
	Part* pPart = GetPart(PART_BUFF);
	if (pPart)
	{
		return pPart->BuffEffect_HasBuffBag(stateBagId);
	}
	return false;
}

void Monster::BuffEffect_ReduceDamage(Creature* pAttack, uint32_t skillId, int32_t &damage)
{
	if (HasBuffStateReduceDamage())
	{
		Part* pPart = GetPart(PART_BUFF);
		if (pPart)
		{
			return pPart->BuffEffect_ReduceDamage(pAttack, skillId, damage);
		}
	}
}

void Monster::BuffEffect_AddExtraDamage(Creature* pBeAttacked, uint32_t skillId, int32_t &damage)
{
	if (HasBuffStateAddExtraDamage())
	{
		Part* pPart = GetPart(PART_BUFF);
		if (pPart)
		{
			return pPart->BuffEffect_AddExtraDamage(pBeAttacked, skillId, damage);
		}
	}
}

bool Monster::TransScene(uint32_t scenceId, Point3<float>& dstPos, uint32_t mapId, STransParam &transParam)
{
	if (!m_pPart[PART_MOVE])
		return false;
	MovePart *pMove = dynamic_cast<MovePart*>(m_pPart[PART_MOVE]);
	return pMove->TransScene(scenceId, dstPos, mapId, transParam);
}

void Monster::StopMove(bool isBroadClent)
{
	if (!m_pPart[PART_MOVE])
		return;
	MovePart *pMove = dynamic_cast<MovePart*>(m_pPart[PART_MOVE]);
	if (isBroadClent)
	{
		return pMove->StopMove();
	}
	else
		return pMove->StopSelfMove();
}

bool Monster::MoveTo(Point3<float> dstPos)
{
	if (!m_pPart[PART_MOVE])
		return false;
	MovePart *pMove = dynamic_cast<MovePart*>(m_pPart[PART_MOVE]);
	return pMove->MoveTo(dstPos);
}

//瞬间移动
bool Monster::Teleporting(Point3<float> dstPos)
{
	if (!m_pPart[PART_MOVE])
		return false;
	MovePart *pMove = dynamic_cast<MovePart*>(m_pPart[PART_MOVE]);
	return pMove->Teleporting(dstPos);
}

//被击退
bool Monster::BeatBack(Point3<float> dstPos)
{
	if (!m_pPart[PART_MOVE])
		return false;
	MovePart *pMove = dynamic_cast<MovePart*>(m_pPart[PART_MOVE]);
	return pMove->BeatBack(dstPos);
}

//bool Monster::AddStateBag(uint32_t skillid, uint32_t lev, ProtoBuf::BuffBagDetailInfo* pClientStatebag, Creature* pTarget /* = nullptr */)
//{
//	SkillPart *pSkillPart = dynamic_cast<SkillPart*>(m_pPart[PART_SKILL]);
//	if (!pSkillPart)
//		return false;
//	return pSkillPart->AddStateBag(skillid, lev, pClientStatebag, pTarget);
//}


void Monster::BuffEffect_CleanupAllFadeOutEffects(BuffInfoEndType endType)
{
	BuffPart* pBuffPart = static_cast<BuffPart*>(GetPart(PART_BUFF));
	if (pBuffPart)
	{
		pBuffPart->BuffEffect_CleanupAllFadeOutEffects(endType);
	}
}

//判断跟isFriend有点区别
void Monster::AddSeeNewCreature(Creature* pCreature)
{
	if (IsDead())
	{
		return;
	}

	if (IsMonsterTa())
	{
		return;
	}

	if (pCreature->CreatureKind() == CREATURE_PLAYER
			|| pCreature->CreatureKind() == CREATURE_NPC
			|| pCreature->CreatureKind() == CREATURE_MONSTER)
	{
		if (!IsFriendSide(pCreature))
		{
			if (m_aiData)
			{
				if (GetParentMonsterType() == PARENT_MONSTER_TYPE_MOVE_BIAOCHE_MONSTER)
				{
					if (pCreature->CreatureKind() == CREATURE_PLAYER)
					{
						if (pCreature->HasBuffState(CREATURE_BUFF_STATE_INVISIBLE))
						{
							if (HasBuffState(CREATURE_BUFF_STATE_SEEINVISIBLE))
							{
								m_aiData->AddHateTarget(pCreature->GetCid(), 10, 0);
							}
						}
						else
						{
							m_aiData->AddHateTarget(pCreature->GetCid(), 10, 0);
						}
						return;
					}
				}
				if (pCreature->CreatureKind() == CREATURE_MONSTER)
				{
					//主动怪优先攻击TA
					Monster* pMonster = dynamic_cast<Monster*>(pCreature);
					if (pMonster && pMonster->IsMonsterTa())
					{
						m_aiData->AddHateTarget(pCreature->GetCid(), 4, 0);
					}
				}

				if (m_monsterGroupId > 0)
				{
					auto pGroup = g_GetCreatureMgr()->GetMonsterGroup(m_sceneId, m_monsterGroupId);
					for(auto it = pGroup->begin(); it != pGroup->end(); it++)
					{
						Monster* pOther = *it;
						if (pOther && pOther->IsDead() == false)
						{
							if (pOther->GetAiData())
							{
								if (pCreature->HasBuffState(CREATURE_BUFF_STATE_INVISIBLE))
								{
									if (HasBuffState(CREATURE_BUFF_STATE_SEEINVISIBLE))
									{
										pOther->GetAiData()->AddHateTarget(pCreature->GetCid(), 0, 0);
									}
								}
								else
								{
									pOther->GetAiData()->AddHateTarget(pCreature->GetCid(), 0, 0);
								}
							}
						}
					}
				}

				//怪物仇恨值唤醒
				if (GetMonsterInfo()->wakeupRadius > 0 && m_aiData->GetHateList().IsEmpty())
				{
					std::list<CharIDType> clist;
					GetScene()->FindCreatureInCircle(clist, GetPos(), GetMonsterInfo()->wakeupRadius / 1000.0f);
					for(auto it = clist.begin(); it != clist.end(); it++)
					{
						if (*it != GetCid())
						{
							Creature* pWakeUpCreature = GetScene()->GetCreature(*it);
							if (pWakeUpCreature &&
								pWakeUpCreature->CreatureKind() == CREATURE_MONSTER && pWakeUpCreature->IsDead() == false)
							{
								if (pWakeUpCreature->GetAiData() && pWakeUpCreature->GetAiData()->GetHateList().IsEmpty())
								{
									if (pCreature->HasBuffState(CREATURE_BUFF_STATE_INVISIBLE))
									{
										if (HasBuffState(CREATURE_BUFF_STATE_SEEINVISIBLE))
										{
											pWakeUpCreature->GetAiData()->AddHateTarget(pCreature->GetCid(), 0, 0);
										}
									}
									else
									{
										pWakeUpCreature->GetAiData()->AddHateTarget(pCreature->GetCid(), 0, 0);
									}
								}
							}
						}
					}
				}

				if (pCreature->HasBuffState(CREATURE_BUFF_STATE_INVISIBLE))
				{
					if (HasBuffState(CREATURE_BUFF_STATE_SEEINVISIBLE))
					{
						m_aiData->AddHateTarget(pCreature->GetCid(), 0, 0);
					}
				}
				else
				{
					m_aiData->AddHateTarget(pCreature->GetCid(), 0, 0);
				}
			}
		}
	}
}

bool Monster::ViewFliter(Creature* pCreature, float dict)
{
	//普通的生物对象只需要裁剪两种情况
	//第一种情况就是对方生物是否可以被见
	//if (pCreature->IsDead())
	//{
	//	return true;
	//}

//	Point3<float> dir =pCreature->GetPos()-m_pos;
//	//LogDebugFmtPrint("cid=%llu,pos=(%f,%f,%f),othercid=%llu,pos=(%f,%f,%f)",m_Cid,m_pos.x,m_pos.y,m_pos.z,pCreature->GetCid(),pCreature->GetPos().x,pCreature->GetPos().y,pCreature->GetPos().z);
//	//判断视野类型
//	if (m_monsterCfgInfo->viewType == ENUM_MONSTER_VIEW_TYPE_CIRCLE)
//	{
//		if (!m_pScene->InCircle(pCreature->GetPos(), m_pos, m_sightRange))
//		{
//			return true;
//		}
//	}
//	else if	(m_monsterCfgInfo->viewType == ENUM_MONSTER_VIEW_TYPE_BALL)
//	{
//		float dict = point2LengthSquare(m_pos, pCreature->GetPos());
//		if (dict > m_sightRange*m_sightRange)
//		{
//			return true;
//		}
//	}
//	else if (m_monsterCfgInfo->viewType == ENUM_MONSTER_VIEW_TYPE_SECTOR)
//	{
//		if (!m_pScene->InSector(m_pos,dir,pCreature->GetPos(),m_viewAngle,m_sightRange))
//		{
//			return true;
//		}
//
//	}

	//专属怪，直接判断,要么看得见，要么看不见
	if (IsOnlyOnwerOnePlayerMonster())
	{
		if (IsOnlyMineMonster(pCreature->GetCid()) && dict <= MAX_CHARACTER_SINGLERANGE_SQUARE)
		{
			return false;
		}
		else
		{
			return true;
		}
	}

	

	return Creature::ViewFliter(pCreature, dict);
}


void Monster::OnTimer(uint32_t nTimerID)
{
	switch (nTimerID)
	{
	case enTimeID_PropTIme:
		if (!IsDead())
		{
			m_dropState = MOnsterDropOwnerState_Owner;
		}
		break;
	case enTimeID_OnwerTime:
		{
			if (!IsDead())
			{
				m_dropState = MonsterDropOwnerState_None;
				m_dropOwnerID = 0;
			}
		}
		break;
	case enTimeID_ExistTime:
	{
		if (!IsDead())
		{
			SetAttr(C_HP, 0, false);
		}
		
	}
	break;
	case enTimeID_CorpseTime:
	{
		OnCorpse();
	}
	break;
	case enTimeID_BornFlag:
	{
		m_bIsBornFlag = false;
	}
	break;
	default:
		break;
	}

}


void Monster::OnExecute(uint16_t nEventID, uint64_t nSrcID, uint8_t bySrcType, void *pContext, int32_t nLen)
{
	switch (nEventID)
	{
	case EVENT_ATTACK_SOMEBODY:
	{
		skillAttackEvent * pEvent = static_cast<skillAttackEvent*>(pContext);
		if (pEvent)
		{
			AddSummonHateCid(pEvent->victim);
		}
	}
	break;
	case EVENT_UNDER_ATTACK:  //自已的被击事件
		{
			skillAttackEvent * pEvent = static_cast<skillAttackEvent*>(pContext);
			if (pEvent)
			{
				AddSummonHateCid(pEvent->attacker);
				if (m_dropState == MonsterDropOwnerState_None)
				{
					//判断有没有掉落归属保护时间
					if (m_monsterCfgInfo->protectTime>0)
					{
						m_dropState = MonsterDropOwnerState_Prop;
						//启定时器
						g_GetTimerAxis()->SetTimer(enTimeID_PropTIme, m_monsterCfgInfo->protectTime, this, 1);
					}
					else
					{
						OnEnterDropTime(pEvent->attacker);
					}
				}
				else if (m_dropState == MOnsterDropOwnerState_Owner)
				{
					if (m_dropOwnerID==0 || pEvent->attacker == m_dropOwnerID)
					{
						//重新进入归属权状态
						OnEnterDropTime(pEvent->attacker);
					}
				}
			}
		}
		break;
	default:
		break;
	}
	
}

void Monster::OnEnterDropTime(uint64_t dropOnwerID)
{
	g_GetTimerAxis()->KillTimer(enTimeID_OnwerTime, this);
	m_dropState = MOnsterDropOwnerState_Owner;

	Creature * pCreature = m_pScene->GetCreature(dropOnwerID);
	if (!pCreature)
	{
		return;
	}

	{
		m_dropOwnerID = dropOnwerID;
	}
	

	
	//启归属权倒计时
	const ConstantConstantCfgInfo *pDropOnwerTimeCfg = g_GetConstantConstantCfgTable()->GetConstantConstantCfgInfo(EArg_DropOwnerTime);
	if (nullptr == pDropOnwerTimeCfg)
	{
		LogErrFmtPrint("[logic] Monster::OnEnterDropTime.....nullptr == pDropOnwerTimeCfg, id:%d ", EArg_DropOwnerTime);
		return ;
	}

	g_GetTimerAxis()->SetTimer(enTimeID_OnwerTime,pDropOnwerTimeCfg->constantdata*1000,this,1);

	LogDebugFmtPrint("monster dropownerid=%llu",m_dropOwnerID);
}

//void Monster::AddSeeLst(CharIDType cid)
//{
//	Creature::AddSeeLst(cid);
//	Creature *pCreature = m_pScene->GetCreature(cid);
//	if (!pCreature)
//		return;
//
//	if (IsDead())
//	{
//		return;
//	}
//
//	if (pCreature->CreatureKind() == CREATURE_PLAYER)
//	{
//		m_beenSeePlayerlst.push_back(cid);
//		if (m_aiData)
//		{
//			m_aiData->Update();
//		}
//	}
//}

//void Monster::DelBeenSeeLst(CharIDType cid)
//{
//	Creature::DelBeenSeeLst(cid);
//	Creature *pCreature = m_pScene->GetCreature(cid);
//	if (!pCreature)
//		return;
//	if (pCreature->CreatureKind() == CREATURE_PLAYER)
//	{
//		m_beenSeePlayerlst.remove(cid);
//	}
//}

//bool Monster::BeenSeeByPlayer()
//{
//	return m_beenSeeLst.empty() == false;
//}

bool Monster::IsFriendSide(Creature* pCreature)
{
	if (pCreature == nullptr ||pCreature == this)
	{
		return true;
	}
	//如果有可以传送的怪，在传送刚过去的时候，不能攻击，除非他移动
	if (!pCreature->GetBeAttackFlag())
	{
		return true;
	}

	if (pCreature->HasBuffState(CREATURE_BUFF_STATE_WUDI))
	{
		return true;
	}

	if (pCreature->CreatureKind() != CREATURE_PLAYER
		&& pCreature->CreatureKind() != CREATURE_MONSTER
		&& pCreature->CreatureKind() != CREATURE_REBOT
		&& pCreature->CreatureKind() != CREATURE_NPC)
	{
		return true;
	}


#ifdef AI_MONSTER_VS_MONSTER
	if (pCreature->CreatureKind() == CREATURE_MONSTER || pCreature->CreatureKind() == CREATURE_PLAYER)
	{
		return false;
	}
	return true;
#endif

	//需要特殊处理的情况

	//如果我是一只召唤物， 主人在的时候就依据主人来判断
	if (GetParentMonsterType() == PARENT_MONSTER_TYPE_SUMMON)
	{
		if (GetMonsterMasterCID() == pCreature->GetCid())
		{
			return true;
		}

		//主人在的时候就依据主人来判断
		if (GetMonsterMasterKind() == CREATURE_PLAYER)
		{
			Creature* pOwner = GetScene()->GetCreature(GetMonsterMasterCID());
			if (pOwner && pOwner != this)
			{
				return pOwner->IsFriendSide(pCreature);
			}
		}
	}
	else if (GetParentMonsterType() == PARENT_MONSTER_TYPE_MOVE_BIAOCHE
			|| GetParentMonsterType() == PARENT_MONSTER_TYPE_MOVE_TEAM_BIAOCHE)
	{
		return true;
	}
	else if (GetParentMonsterType() == PARENT_MONSTER_TYPE_MOVE_BIAOCHE_MONSTER)
	{
		if (pCreature->CreatureKind() == CREATURE_MONSTER)
		{
			Monster* pMonster = dynamic_cast<Monster*>(pCreature);
			if (pMonster)
			{
				if (pMonster->GetParentMonsterType() == PARENT_MONSTER_TYPE_MOVE_BIAOCHE)
				{
					if (this->GetMonsterMasterCID() > 0 && this->GetMonsterMasterCID() == pMonster->GetMonsterMasterCID())
					{
						return false;
					}
				}
				else if (pMonster->GetParentMonsterType() == PARENT_MONSTER_TYPE_MOVE_TEAM_BIAOCHE)
				{
					if (this->GetMonsterUnionID() > 0 && this->GetMonsterUnionID() == pMonster->GetMonsterUnionID())
					{
						return false;
					}
				}

				return true;
			}
		}
		else if (pCreature->CreatureKind() == CREATURE_NPC)
		{
			return true;
		}
		//玩家和镖车怪物的关系
		else if (pCreature->CreatureKind()== CREATURE_PLAYER)
		{
			Player * pPlayer = dynamic_cast<Player*>(pCreature);
			if (pPlayer)
			{
				if (!pPlayer->IsCanBeAttackByCurrentPos())
				{
					return true;
				}

				//公会镖车怪
				if (this->GetMonsterUnionID() > 0)
				{
					if (pPlayer->GetAttr(C_UNION_ID) > 0)
					{
						if (this->GetMonsterUnionID() == pPlayer->GetAttr(C_UNION_ID))
						{
							return false;
						}
					}
				}
				else //个人镖车
				{
					if (this->GetMonsterMasterCID() == pPlayer->GetCid())
					{
						return false;
					}
					else
					{
						Player* pOwner = g_GetCreatureMgr()->GetPlayer(GetMonsterMasterCID());
						if (pOwner && pOwner->GetAttr(C_TEAM_ID) > 0 && pOwner->GetAttr(C_TEAM_ID) == pPlayer->GetAttr(C_TEAM_ID))
						{
							return false;
						}
					}
				}
			}
		}
	}

	//如果对方是一直召唤物，如果对方不可被攻击，返回true, 如果主人存在就 依据主人
	if (pCreature->CreatureKind() == CREATURE_MONSTER)
	{
		Monster* pMonster = dynamic_cast<Monster*>(pCreature);
		if (pMonster)
		{
			if (pMonster->GetParentMonsterType() == PARENT_MONSTER_TYPE_SUMMON)
			{
				if (pMonster->GetMonsterMasterCID() == GetCid())
				{
					return true;
				}
				//如果对方不可被攻击，返回true
				if (pMonster->GetMonsterFightType() == SUMMON_MONSTER_TYPE_CANNOT_BEATTACK_CANNOT_MOVE
						|| pMonster->GetMonsterFightType() == SUMMON_MONSTER_TYPE_CANNOT_BEATTACK_CAN_MOVE)
				{
					return true;
				}

				if (pMonster->GetMonsterMasterKind() == CREATURE_PLAYER)
				{
					//如果主人存在就 依据主人
					Creature* pOwner = GetScene()->GetCreature(pMonster->GetMonsterMasterCID());
					if (pOwner && pOwner != this)
					{
						return IsFriendSide(pOwner);
					}
				}
			}
		}
		else if (pMonster->GetParentMonsterType() == PARENT_MONSTER_TYPE_MOVE_BIAOCHE
				|| pMonster->GetParentMonsterType() == PARENT_MONSTER_TYPE_MOVE_TEAM_BIAOCHE)
		{
			return true;
		}
		else if (GetParentMonsterType() == PARENT_MONSTER_TYPE_MOVE_BIAOCHE_MONSTER)
		{
			return true;
		}
	}
	else if (pCreature->CreatureKind()== CREATURE_NPC)
	{
		Npc* pNpc = dynamic_cast<Npc*>(pCreature);
		if (pNpc && pNpc->GetNpcInfo()->npcFightType == 0)
		{
			return true;
		}
	}
	//玩家的关系
	else if (pCreature->CreatureKind()== CREATURE_PLAYER)
	{
		Player * pPlayer = dynamic_cast<Player*>(pCreature);
		if (pPlayer)
		{
			if (!pPlayer->IsCanBeAttackByCurrentPos())
			{
				return true;
			}
		}
	}

	//通过表格探寻其他关系
	int first = gGetCreatureFriendShip(this);
	int second = gGetCreatureFriendShip(pCreature);
	return gGetCreatureVsCreature(first, second);
}


//路径
void Monster::SetAiPath(uint32_t pathId,int8_t patroType)
{
	if (nullptr!= m_aiData)
	{
		const PathRefLocation *pathLoc = g_GetMapLocationCfg()->GetPathRefLoc(pathId);
		if (nullptr != pathLoc)
		{
			m_aiData->GetPatrolPath().AddPatrolPath(pathLoc->m_vecPos, patroType);
			m_aiData->SetAiEnable(true);
		}		
	}
}

//获取怪物模型半径
float Monster::GetModelRadius()
{
	if (!m_monsterCfgInfo)
	{
		return 0;
	}
	return (float)m_monsterCfgInfo->modelRadius / 1000.0f *m_modelScale.x;
}

void Monster::GetHateListID(VEC_UINT64& hastIds)
{
	if (m_aiData)
	{
		auto hateTargetList = m_aiData->GetHateList().GetHateList();
		for (auto iter = hateTargetList.begin(); iter != hateTargetList.end(); ++iter)
		{
			Player* pPlayer = m_pScene->GetPlayer(iter->m_hateTargetCid);

			if (!pPlayer)
			{
				continue;
			}

			if (point2Length(GetPos(), pPlayer->GetPos()) > g_hateDistance)
			{
				continue;
			}

			hastIds.push_back(iter->m_hateTargetCid);
		}
	}
}
void Monster::SetMonsterUnionID(uint32_t unionID)
{
	m_stExtendInfo.set_unionid(unionID);
	if (m_aiData)
	{
		m_aiData->SetUnionId(unionID);
	}
}

void Monster::SetMonsterMasterKind(int creatureKind)
{
	m_stExtendInfo.set_mastercreaturekind(creatureKind);
}

void Monster::SetMonsterMasterCID(CharIDType masterID)
{
	m_stExtendInfo.set_mastercid(masterID);
	if (m_aiData)
	{
		m_aiData->SetOwnerCid(masterID);
	}
}

void Monster::SetMonstaeMasterName(std::string strName)
{
	m_stExtendInfo.set_mastername(strName);
}
void Monster::SetMonsterCampID(uint32_t campID)
{
	m_stExtendInfo.set_campid(campID);
	if (m_aiData)
	{
		m_aiData->SetCampId(campID);
	}
}

void Monster::SetMonsterTeamID(uint32_t teamID)
{
	m_stExtendInfo.set_teamid(teamID);
}


//是否是专属怪
bool Monster::IsOnlyOnwerOnePlayerMonster()
{
	if (m_monsterCfgInfo)
	{
		if (m_monsterCfgInfo->isBelongToMe)
		{
			return true;
		}
	}

	return false;
}


//是否是自己的专属怪,或是属于自己队伍的专属怪
bool Monster::IsOnlyMineMonster(CharIDType cid)
{
	
	if (IsOnlyOnwerOnePlayerMonster())
	{
		Player * pPlayer = g_GetCreatureMgr()->GetPlayer(cid);
		if (pPlayer)
		{
			if (m_stExtendInfo.mastercid() == cid || (m_stExtendInfo.teamid() > 0 && m_stExtendInfo.teamid() == pPlayer->GetAttr(C_TEAM_ID)))
			{
				return true;
			}
		}
	}
		
	return false;
}

uint32_t Monster::GetMonsterUnionID()
{
	return m_stExtendInfo.unionid();
}

int Monster::GetMonsterMasterKind()
{
	return m_stExtendInfo.mastercreaturekind();
}

CharIDType Monster::GetMonsterMasterCID()
{
	return m_stExtendInfo.mastercid();
}

std::string Monster::GetMasterName()
{
	return m_stExtendInfo.mastername();
}

void Monster::SetModelScale(const Point3<float> & pos)
{
	if (pos != Point3<float>())
		m_modelScale = pos;
	else
		m_modelScale = Point3<float>(1,1,1);
}

uint32_t Monster::GetMonsterCampID()
{
	return m_stExtendInfo.campid();
}

std::vector<uint64_t> Monster::GetMonsterKillerList(std::map<uint32_t, std::vector<uint64_t> > * mapTeamPlayer)
{
	std::vector<uint64_t> playerList;
	std::vector<uint32_t> vTeamID;
	//BEGIN_PROFILE("Monster::GetMonsterKillerList");
	CreatureCommonAI* pAiData = GetAiData();
	if (!pAiData)
	{
		return playerList;
	}
	auto & tmpList = pAiData->GetHateList().GetHateList();

	std::list<HateTargetData>::iterator iter = tmpList.begin();

	for (; iter != tmpList.end(); ++iter)
	{

		//没打出伤害的人，不计算在仇恨列表中
		if (iter->m_damageValue <= 0)
		{
			continue;
		}

		Player * pPlayer = g_GetCreatureMgr()->GetPlayer(iter->m_hateTargetCid);

		if (!pPlayer)
		{
			continue;
		}

		if (point2Length(GetPos(), pPlayer->GetPos()) > g_constCalcExpRang)
		{
			continue;
		}

		//找出仇恨列表中有队伍的玩家队伍ID
		uint32_t teamid = pPlayer->GetAttr(C_TEAM_ID);
		if (teamid > 0)
		{
			if (std::find(vTeamID.begin(),vTeamID.end(),teamid)==vTeamID.end())
			{
				vTeamID.push_back(teamid);
			}

			if (mapTeamPlayer)
			{
				if ((*mapTeamPlayer).find(teamid) == (*mapTeamPlayer).end())
				{
					std::vector<uint64_t> vPlayerID;
					vPlayerID.push_back(iter->m_hateTargetCid);
					(*mapTeamPlayer)[teamid] = vPlayerID;
				}
				else
				{
					(*mapTeamPlayer)[teamid].push_back(iter->m_hateTargetCid);
				}
			}
		}

		playerList.push_back(iter->m_hateTargetCid);
	}

	
	//找出要怪物附近的所有玩家，在队列里的
	//BEGIN_PROFILE("Monster::find teamlist");
	Scene * pScene = GetScene();
	if (pScene)
	{
		
		CidLst list;
		pScene->FindCreatureInCircle(list, GetPos(), g_constCalcExpRang);

		CidLst::iterator iter = list.begin();
		for (; iter != list.end(); ++iter)
		{
			Creature * pCreate = pScene->GetCreature(*iter);
			if (pCreate && pCreate->CreatureKind() == CREATURE_PLAYER)
			{
				Player * pPlayer = dynamic_cast<Player*>(pCreate);
				if (pPlayer)
				{
					uint32_t teamID = pPlayer->GetAttr(C_TEAM_ID);
					if (teamID > 0)
					{
						if (std::find(vTeamID.begin(), vTeamID.end(), teamID) !=vTeamID.end() )
						{
							if (std::find(playerList.begin(), playerList.end(), *iter) == playerList.end())
							{
								playerList.push_back(*iter);
								if (mapTeamPlayer)
								{
									(*mapTeamPlayer)[teamID].push_back(*iter);
								}
							}
						}
					}
				}//(pPlayer)
			}
		}
	}
	//END_PROFILE();
	//如果是有主人的，要把主人加进去
	//if (m_stExtendInfo.mastercid()>0)
	//{
	//	if (std::find(playerList.begin(), playerList.end(), m_stExtendInfo.mastercid()) == playerList.end())
	//	{
	//		playerList.push_back(m_stExtendInfo.mastercid());
	//	}
	//}

	//END_PROFILE();

	return playerList;
}

//更新死亡击飞状态
bool Monster::UpdateDeadBeback()
{
	if (m_monsterCfgInfo && m_monsterCfgInfo->isSkin <= 0)
	{
		m_bIsDeadBeback = true;
		return true;
	}

	return false;
}

//根据配置的公式算出该怪物属性值
uint64_t Monster::GetMonsterAttrFormula(VEC_INT32  &outPara)
{
	if (outPara.size()==0)
	{
		return 0;
	}
	else if (outPara.size() == 1)
	{
		return outPara[0];
	}
	else
	{
		if (outPara[0]== 1) //是公式1
		{
			if (outPara.size()!=4)
			{
				LogDebugFmtPrint("Monster::GetMonsterAttrFormula param error num=4" );
				return 0;
			}
			return m_stExtendInfo.level()  * m_stExtendInfo.level()*outPara[1] / 100.0 + outPara[2]/100.0 * m_stExtendInfo.level() + outPara[3]/100.0;
		}
	}
	return 0;
}

uint32_t Monster::GetConfigId()
{
	return m_monsterId;
}

//处理怪物死亡，出身时触发事件
bool Monster::OnDoEffect(bool isBorn)
{
	std::vector<int32_t> vEffectID;
	if (isBorn)
	{
		CommonApi::SplitStrToVecInt(m_monsterCfgInfo->bornTrigger, ",", &vEffectID);
	}
	else
	{
		CommonApi::SplitStrToVecInt(m_monsterCfgInfo->deathTrigger, ",", &vEffectID);
	}

	for (int i = 0; i < (int)vEffectID.size();++i)
	{
		//触发出身效果
		g_GetEffectMgr()->OnEffect(this, (EffectIDType)vEffectID[i]);
	}
	
	return true;
}

void Monster::StopAI()
{
	if (m_aiData)
	{
		m_aiData->StopAI();
	}
}


void Monster::AddAttackMonsterTarget(float dict,Creature * pTarget)
{
	if (GetParentMonsterType() == PARENT_MONSTER_TYPE_MONSTER
		&& GetMonsterFightType() == ENUM_MONSTER_FIGHT_TYPE_ACTIVE_ATTACK)
	{
		if (dict <= GetSightRange() * GetSightRange() &&
			GetAiData() && GetAiData()->IsHateListEmpty())
		{
			AddSeeNewCreature(pTarget);
			if (GetAiData()->HasHateListPlayer())
			{
				GetAiData()->SetAllSkillsCds();
			}
		}
	}
}

bool Monster::IsCanBoPi()
{
	if (m_monsterCfgInfo)
	{
		return m_monsterCfgInfo->isSkin;
	}
	return false;
}

uint64_t Monster::GetKillerID()
{
	return m_i64KillerID;
}


